package com.antdant.service;

import com.antdant.entity.Comment;
import com.antdant.entity.User;
import com.antdant.repository.CommentsRepository;
import com.antdant.utils.DataUtils;
import com.antdant.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/3/2 16:24
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class CommentsService {

    @Resource
    private CommentsRepository commentsRepository;

    @Resource
    private ReplyService replyService;

    /**
     * 返回评论分页数据
     *
     * @param current
     * @param size
     * @param comment
     * @return
     */
    public Page<Comment> getAllComments(Integer current, Integer size, Comment comment) {
        Sort sort = Sort.by(Sort.Direction.DESC, "supportCount");//根据点赞降序排列
        Pageable pageable = PageRequest.of(current - 1, size, sort);
        return commentsRepository.findAll(new Specification<Comment>() {
            @Override
            public Predicate toPredicate(Root<Comment> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (comment.getCourseId() != -1) {
                    list.add(criteriaBuilder.equal(root.get("courseId"), comment.getCourseId()));//根据课程id检索
                }
                if (DataUtils.isNotEmptyStr(comment.getContent())) {
                    list.add(criteriaBuilder.like(root.get("content"), comment.getContent()));
                }
                if (DataUtils.isNotEmptyStr(comment.getUserName())) {
                    list.add(criteriaBuilder.like(root.get("userName"), comment.getUserName()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    /**
     * 根据评论id删除评论
     *
     * @param commentId 需要被删除评论的id
     * @return
     */
    public boolean deleteCommentById(Integer commentId) {
        try {
            commentsRepository.deleteById(commentId);
            return replyService.deleteReplyByToWhich(commentId); //删除相关回复
        } catch (RuntimeException e) {
            return false;
        }
    }

    /**
     * 点赞+1
     *
     * @param commentId
     * @return
     */
    public Comment addSupport(Integer commentId) {
        Comment comment = commentsRepository.findById(commentId).orElse(null);
        assert comment != null;
        Integer supportCount = comment.getSupportCount() + 1;
        comment.setSupportCount(supportCount);
        return commentsRepository.saveAndFlush(comment);
    }

    /**
     * 回复数+1
     *
     * @param commentId
     * @return
     */
    public Comment addReplyCount(Integer commentId) {
        Comment comment = commentsRepository.findById(commentId).orElse(null);
        assert comment != null;
        Integer replyCount = comment.getReplyCount() + 1;
        comment.setReplyCount(replyCount);
        return commentsRepository.saveAndFlush(comment);
    }

    /**
     * 新增一条评论
     *
     * @param comment
     * @param user
     * @return
     */
    public Comment addNewComment(Comment comment, User user) {
        Comment newComment = createNewComment();
        newComment.setCourseId(comment.getCourseId());
        newComment.setContent(comment.getContent());
        newComment.setAvatar(user.getAvatar());
        newComment.setUserId(user.getId());
        newComment.setUserName(user.getUsername());
        newComment.setIsManager(user.getIsManager());
        return commentsRepository.saveAndFlush(newComment);
    }

    /**
     * 新评论初始化
     *
     * @return
     */
    private Comment createNewComment() {
        Comment comment = new Comment();
        comment.setCreateTime(DateUtils.getNowTime());
        comment.setSupportCount(0);
        comment.setReplyCount(0);
        return comment;
    }

    /**
     * 根据评论id返回当前评论
     *
     * @param commentId
     * @return
     */
    public Comment getCommentById(Integer commentId) {
        return commentsRepository.findById(commentId).orElse(null);
    }

    /**
     * 更新评论
     *
     * @param comment
     * @return
     */
    public Comment updateComment(Comment comment) {
        return commentsRepository.saveAndFlush(comment);
    }

    /**
     * 授权用户为管理员,跟新评论信息
     *
     * @param applyFromId
     */
    public void toBeManager(Integer applyFromId) {
        List<Comment> comments = commentsRepository.findAll(new Specification<Comment>() {
            @Override
            public Predicate toPredicate(Root<Comment> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate temp = criteriaBuilder.equal(root.get("userId"), applyFromId);
                return temp;
            }
        });
        for (Comment comment : comments) {
            comment.setIsManager(1);
            commentsRepository.saveAndFlush(comment);
        }
    }
}
